class DerbyController < ApplicationController
  attr_accessor :the_grid_ar_object, :grid_layout
  def recent_event_listings()
    @events = Event.get_recent_events_summary()
    puts "This is so full of PAIN: ", @events.to_json(:include => :games)
  end

  #Create a fully functional event browser div that can be inserted into anything.
  def create_event_browser()
    @events = Event.get_recent_events_summary()
    #Use a layout if one is requested.
    common_grid_opts(@events)
  end

  def create_team_browser()
    @teams = Team.find(:all);
    common_grid_opts(@teams)
  end

  def create_game_browser()
    @games = Game.find(:all)
    common_grid_opts(@games)
  end

  def create_game_display
    @games = Game.find(:all, :include => [:scores])
    
    #A game display is useless without a set of teams and their point totals.  Thus we need to make an array of hashes that 
    #takes this fact into account and setups up a valid grid layout.
    #[game: name, Winner: game.teams.first[:identifier], WinnerTotal: game.scores[:points], LosingTeam: name, LosingScore: score]
    game_array = Array.new()
    @games.each{|game| 
      scores = game.scores

      game_array <<  {
          :id     => game[:id],
          :name   => game[:name],
          :pointsA => scores[0][:points], 
          :teamA   => scores[0][:identifier],
          :pointsB => scores[1][:points], 
          :teamB  => scores[1][:identifier]
        }
    }
    @games       = game_array.to_json()
    @grid_layout = "[
                     { name: \'name\' , field: \'name\', rowSpan: 2},
                     { name: \'id\', field: \'id\', rowSpan: 2},
                     { name: \'teamA\' , field: \'teamA\' },
                     { name: \'points\' , field: \'pointsA\' }
                    ],
                    [
                     { name: \'teamB\' , field: \'teamB\' },
                     { name: \'points\' , field: \'pointsB\' }
                    ]"

                     
#                     
#                    ],
  end

  def common_grid_opts(ar_obj, rows=nil)
    @div_id = (params[:div_id] ? params[:div_id] : false) 
    if (rows.nil?) 
      @grid_layout = common_grid_setup(ar_obj)
    end
    render :layout => (params[:layout] ? params[:layout] : false)
  end

  def common_grid_setup(ar_objects)
    rows = ar_objects.first.attributes.keys
    return (rows.collect! { |val| "{name: \'#{val}\', field: \'#{val}\'}"}).join(",")
  end

end
